#!/bin/bash -ex

SCRIPT_DIR=$(realpath "$(dirname "${0}")")

NODE_MODULE_PANDA="/home/aleks/repos/idlize/external/incremental/tools/panda/node_modules/@panda/"
NODE_MODULE_PANDA_BIN="${NODE_MODULE_PANDA}/sdk/linux_host_tools/bin/"

LOCAL_BUILD_PANDA="/home/aleks/build_dirs/panda_sdks_buids/sdk_20250328_host_debug/linux_host_tools/"
LOCAL_BUILD_PANDA_BIN="${LOCAL_BUILD_PANDA}/bin"

# DEF_PATH_BIN="${NODE_MODULE_PANDA_BIN}"
DEF_PATH_BIN="${LOCAL_BUILD_PANDA_BIN}"

# ETSSTDLIB_ABC="${NODE_MODULE_PANDA}/sdk/ets/etsstdlib.abc"
ETSSTDLIB_ABC="${LOCAL_BUILD_PANDA}/plugins/ets/etsstdlib.abc"

ES2PANDA="${DEF_PATH_BIN}/es2panda"
PANDA="${DEF_PATH_BIN}/ark"
PANDA_AOT="${DEF_PATH_BIN}/ark_aot"
PANDA_DISASM="${DEF_PATH_BIN}/ark_disasm"
PANDA_LINK="${DEF_PATH_BIN}/ark_link"

BUILD_DIR="${SCRIPT_DIR}/build"

ARKTSCONFIG_PATH="${SCRIPT_DIR}/arktsconfig.json"

SRC_MAIN="${SCRIPT_DIR}/main.ets"

mkdir -p ${BUILD_DIR}
cd ${BUILD_DIR}

rm -rf *

cmake -GNinja ../
ninja calc_lib

OUTPUT_MAIN="${BUILD_DIR}/main.abc"

${ES2PANDA} \
--arktsconfig="${ARKTSCONFIG_PATH}" \
${SRC_MAIN} \
--output="${OUTPUT_MAIN}"

${PANDA_DISASM} ${OUTPUT_MAIN} ${OUTPUT_MAIN}.pa

SAMPLING_OPTIONS="--sampling-profiler-enable --sampling-profiler-interval=1 --sampling-profiler-output-file=${BUILD_DIR}/outfile.aspt --log-level=debug --log-components=profiler"

${PANDA} \
--load-runtimes=ets \
--boot-panda-files="${ETSSTDLIB_ABC}" \
--native-library-path="${BUILD_DIR}" \
${SAMPLING_OPTIONS} \
"${OUTPUT_MAIN}" \
"main.ETSGLOBAL::main"

${SCRIPT_DIR}/../flame_graph_gen.sh "${BUILD_DIR}/outfile.aspt"

echo "WIN_WIN"
